/*
 *全局统一管理用户授权
 * @Author: bobo
 */
import CacheUtil from '@/utils/CryptCacheUtil'


// *******************************常量定义******************************
const KEY_CACHE_ACCESS_TOKEN = "access_token";
const KEY_CACHE_REFRESH_TOKEN = "refresh_token";
const state = {
  accessToken: null,
  expire: 0,
  cacheTime: null,
  isLogin: false,
};

const OauthStore = {

  /**
   * 缓存授权Token
   * @param {string} token 授权token的值
   * @param {number} expire 过期时间，单位:秒  -1永久存储
   */
  saveAccessToken(token, expire) {
    state.accessToken = token;
    state.expire = expire;
    state.cacheTime = new Date();
    CacheUtil.save(KEY_CACHE_ACCESS_TOKEN, token, expire)
  },
  /**
   * 获取授权Token
   */
  getAccessToken() {
    if (state.accessToken != null) {
      //获取已经存储的时间
      let difTime = (new Date().valueOf() - state.cacheTime.valueOf()) / 1000;
      if (difTime > state.expire) {
        state.accessToken = null;
        state.expire = 0;
        state.cacheTime = null;
      }
      return state.accessToken;
    } else {
      return CacheUtil.get(KEY_CACHE_ACCESS_TOKEN);
    }
  },
  /**
   * 缓存刷新Token
   * @param {string} token 刷新token的值
   * @param {number} expire 过期时间，单位:秒  -1永久存储
   */
  saveRefreshToken(token, expire) {
    CacheUtil.save(KEY_CACHE_REFRESH_TOKEN, token, expire)
    state.isLogin = true;
  },
  /**
   * 获取刷新Token
   */
  getRefreshToken() {
    return CacheUtil.get(KEY_CACHE_REFRESH_TOKEN)
  },
  /**
   * 用户是否已经登录
   */
  isLogin() {
    if (state.isLogin) {
      return true;
    } else {
      return this.getRefreshToken() != null;
    }

  }
}
export {
  OauthStore
}